import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/eventbus.dart';
import 'package:enjoy_plus_hm/utils/token.dart';

class NetworkService {
  final _dio = Dio();

  NetworkService() {
    //基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    // 设置请求头
    _dio.options.headers = {'content-type': 'application/json'};
    // 添加请求和响应拦截器
    _addInterceptors();
  }

  // 拦截器
  void _addInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          // 请求拦截器
          final token = TokenManager().getToken() ?? '';
          if (token.isNotEmpty) {
            options.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(options);
        },
        onResponse: (response, handler) {
          // 响应拦截器
          return handler.next(response);
        },
        onError: (DioException error, handler) {
          // 响应拦截器,处理错误
          return handler.next(error);
        },
      ),
    );
  }

  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      final res = await _dio.get(url, queryParameters: params);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> post(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.post(url, data: data);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> put(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.put(url, data: data);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> delete(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.delete(url, data: data);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败,状态码:${response.statusCode}');
    }
  }

  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('请求超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if (error.response?.statusCode == 401) {
          // token失效
          TokenManager().removeToken();
          eventBus.fire(logoutEvent('token失效'));
        } else {
          throw Exception('请求失败,状态码:${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误');
    }
  }
}

final http = NetworkService();
